package com.mdlaser.config;

import lombok.extern.log4j.Log4j2;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.cache.support.CompositeCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;

@Configuration
@EnableCaching
@Log4j2
public class CacheConfig {

    public static boolean enableRedis;

    @Bean
    @Order(1)
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        CompositeCacheManager compositeCacheManager;
        try {
            redisConnectionFactory.getConnection();
            RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory)
                    .build();
            compositeCacheManager = new CompositeCacheManager(redisCacheManager);
            enableRedis = true;
            log.info("已配置redis且连接正常，系统缓存将使用redis");
        } catch (Exception e) {
            log.info("redis服务不可用，系统缓存将使用内存");
            ConcurrentMapCacheManager concurrentMapCacheManager = new ConcurrentMapCacheManager();
            compositeCacheManager = new CompositeCacheManager(concurrentMapCacheManager);
        }
        return compositeCacheManager;

    }


}


